#!/usr/bin/env bash
# -----------------------------------------------------------------------------
# Filename   : resound.sh
# Author     : Monix Systems
# Description: 
# Project    : RESOUND
# License    : MIT
#
# Copyright © 2020 VOXEON	
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the “Software”), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall
# be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# -----------------------------------------------------------------------------

set -eo pipefail

# File data
input_file="$1"
final_file=$(printf "%s" "$input_file" | rev | cut -d '.' -f2-20 | rev)
tmp_dir=$(mktemp -d)

# Media data
input_duration=$(ffprobe -v error \
				   -show_entries format=duration \
				   -of default=noprint_wrappers=1:nokey=1 \
				   "$input_file" \
				   | cut -d '.' -f1)
half_input_duration=$((input_duration / 2))
iterative_khz_freq=10
input_mean_vol=$(ffplay -ss "$half_input_duration" \
				   -t 1.5 \
				   "$input_file" -autoexit -nodisp -af volumedetect,volume=0 2>&1 \
				   | grep mean_volume \
				   | cut -d ':' -f2 \
				   | tr -dc '.\-[:digit:]' \
				   | cut -d '.' -f1)
target_layer_vol=$((input_mean_vol - 40))
test_mean_vol=0

animation()
{
	animation_cells="    ▖▘▝▗▘▝▗▘▝▗▘▝▗▘▝▖▘▝▗▘▝▗▖"

	tput civis
		
	for (( i=0; i<${#animation_cells}; i++ )); do
		sleep 0.05
		echo -en "${animation_cells:0:$i}" "\r"
	done
	
	echo ""
}

function_error_interface()
{
	printf "[ERROR]\nFailed Function: %s\n" "$1"
}

variable_error_interface()
{
	printf "[ERROR]\nProblematic Variable: %s\n" "$1"
	printf "Function: %s\n" "$2"
}

frequency_scan()
{
	test_mean_vol=$(ffplay -ss "$half_input_duration" -t 1.5 \
					  -i "$input_file" \
					  -autoexit -nodisp \
					  -af highpass=${iterative_khz_freq}000,highpass=${iterative_khz_freq}000,volumedetect,volume=0 2>&1 \
					  | grep mean_volume \
					  | cut -d ':' -f2 \
					  | tr -dc '.\-[:digit:]' \
					  | cut -d '.' -f1)
					  
	[ "$test_mean_vol" ] || { >&2 variable_error_interface test_mean_vol frequency_scan; exit 1; }

	((iterative_khz_freq++)) 
	
	[ "$iterative_khz_freq" ] || { >&2 variable_error_interface iterative_khz_freq frequency_scan; exit 1; }

	layer_hf_cutoff="${iterative_khz_freq}000"
}

# Main function

echo "[-] Running frequency scan"

frequency_scan & PID=$!

while kill -0 $PID 2> /dev/null; do
	animation
	sleep 0.5
done

tput cnorm

while [ "$test_mean_vol" -gt "$target_layer_vol" ]; do 
	frequency_scan
done

echo "[-] Upsampling source content"

ffmpeg -i "$input_file" \
	-c:a pcm_f32le \
	-ar 96000 \
	"$tmp_dir"/temp_input.wav 2>/dev/null \
	& PID=$!
	
while kill -0 $PID 2>/dev/null; do
	animation
	sleep 0.5
done

tput cnorm

echo "[-] Generating harmonic data"

rubberband --precise \
	-p 12 "$tmp_dir"/temp_input.wav \
	"$tmp_dir"/temp_input_12s.wav 2>/dev/null \
	& PID=$!

while kill -0 $PID 2>/dev/null; do
	animation
	sleep 0.5
done

tput cnorm

layer_hf_cutoff="${iterative_khz_freq}000"

if [ "$layer_hf_cutoff" -ge 19000 ]; then
	ffmpeg -i "$tmp_dir"/temp_input_12s.wav \
		-af highpass="$layer_hf_cutoff",volume=-13dB \
		"$tmp_dir"/temp_input_12s_HF.wav \
		2>/dev/null \
		& PID=$!
		
	while kill -0 $PID 2>/dev/null; do
		animation
		sleep 0.5
	done
	
	tput cnorm
else
	ffmpeg -i "$tmp_dir"/temp_input_12s.wav \
		-af highpass="$layer_hf_cutoff",highpass="$layer_hf_cutoff",volume=-19dB \
		"$tmp_dir"/temp_input_12s_HF.wav \
		2>/dev/null \
		& PID=$!
		
	while kill -0 $PID 2>/dev/null; do
		animation
		sleep 0.5
	done
	
	tput cnorm
fi
		 
echo "[-] Producing output"
ffmpeg -i "$tmp_dir"/temp_input.wav \
    -i "$tmp_dir"/temp_input_12s_HF.wav \
    -filter_complex amix,volume=6dB \
    -c:a pcm_f32le \
    -ar 96000 \
    "$final_file"_RS.wav 2>/dev/null \
    & PID=$!

while kill -0 $PID 2>/dev/null; do
	animation
	sleep 0.5
done

tput cnorm

rm -rf "$tmp_dir"

echo "[-] Complete"